<script lang="ts" setup name="IkIconPicker">
// MicroApp icon
import IconMicro from '@micro/iconfont/iconfont.json'
const props = withDefaults(
  defineProps<{
    modelValue: string
    width?: number
    height?: number
  }>(),
  {
    modelValue: '',
    width: 100,
    height: 100
  }
)
const emit = defineEmits(['update:modelValue'])
type TIcon = Array<{
  name: string
  class: string
  font_class: string
  font_family: string
}>
const iconInfo: {
  mainIcon: TIcon
  microIcon: TIcon
  svg: TIcon
} = {
  mainIcon: [],
  microIcon: [],
  svg: []
}

const getIconList = (
  icons: {
    css_prefix_text?: string
    font_family?: string
    glyphs?: Array<{ name: string; font_class: string; }>
  },
  type: string
) => {
  const iconList = []
  const { font_family: fm, glyphs, css_prefix_text } = icons
  if (!fm || !glyphs)
    return []
  for (const { name, font_class } of glyphs) {
    iconList.push({
      type,
      name: `${type} ${name}`,
      class: `${css_prefix_text}${font_class}`,
      font_class,
      font_family: fm
    })
  }
  return iconList
}

// iconInfo.mainIcon = getIconList(IconSys, 'icon-sys')
iconInfo.microIcon = getIconList(IconMicro, 'icon-micro')
iconInfo.svg = getIconList((window as any).iking_iconfont_json, 'ik_icon-svg')

const icons = [
  // {
  //   name: '系统图标',
  //   list: iconInfo.mainIcon,
  //   total: iconInfo.mainIcon.length
  // },
  {
    name: '项目图标',
    list: iconInfo.microIcon,
    total: iconInfo.microIcon.length
  },
  {
    name: '双色图标',
    list: iconInfo.svg,
    total: iconInfo.svg.length
  }
]
const dialogVisible = ref(false)
const search = ref('')

const myValue = ref('')
const activeName = ref(
  icons.some(item => item.name === myValue.value)
    ? myValue.value
    : icons[0].name
)

watch(
  () => props.modelValue,
  value => {
    myValue.value = value
  },
  {
    immediate: true
  }
)
const currentIconList: Ref<TIcon> = ref([])
onMounted(() => {
  getCurrentIconList()
})
watch(
  () => search.value,
  val => {
    if (val) {
      const arr = currentIconList.value.filter((item: any) => {
        return (
          item.class.toLowerCase().includes(val.toLowerCase())
          || item.name.toLowerCase().includes(val.toLowerCase())
        )
      })
      return (currentIconList.value = arr)
    }
    else {
      getCurrentIconList()
    }
  }
)

const handleTabChange = () => {
  getCurrentIconList()
}
const getCurrentIconList = () => {
  currentIconList.value
    = icons.find(v => v.name === activeName.value)?.list || []
}

const previewIcon = ref('')
const previewIconIndex = ref(0)
const previewIconPosition = computed(() => {
  return [
    previewIconIndex.value < 18 ? 'top' : 'bottom',
    previewIconIndex.value % 6 >= 3 ? 'left' : 'right'
  ].join('-')
})

// const currentIconList = computed(() => icons.find(v => v.name === activeName.value)?.list || [])

function showPreviewIcon(iconName: string, index: number) {
  previewIcon.value = iconName
  previewIconIndex.value = index
}
function hidePreviewIcon() {
  previewIcon.value = ''
  previewIconIndex.value = 0
}

function chooseIcon(val: string) {
  myValue.value = val
  emit('update:modelValue', val)
  dialogVisible.value = false
}
function removeIcon() {
  myValue.value = ''
  emit('update:modelValue', '')
  dialogVisible.value = false
}
</script>

<template>
  <el-icon
    class="icon-picker"
    :class="{
      empty: !myValue,
    }"
    :style="{ width: `${props.width}px`, height: `${props.height}px` }"
    @click="dialogVisible = true"
  >
    <IkSvgIcon :name="myValue || 'iksvg_xinzeng'" />
  </el-icon>
  <el-dialog
    v-model="dialogVisible"
    class="icon-picker-dialog"
    width="600px"
    draggable
    append-to-body
  >
    <div class="icon-picker-dialog-body">
      <el-tabs
        v-model="activeName"
        tab-position="left"
        class="demo-tabs"
        @tab-change="handleTabChange"
      >
        <el-tab-pane v-for="item in icons" :key="item.name" :name="item.name">
          <template #label>
            <div class="icon-label">
              <div class="name">
                {{ item.name }}
              </div>
              <div class="total">{{ item.total }} 个</div>
            </div>
          </template>
        </el-tab-pane>
      </el-tabs>
      <div class="main-container">
        <div class="search-bar">
          <el-input
            v-model.trim="search"
            size="large"
            placeholder="搜索..."
            clearable
          >
            <template #prefix>
              <IkSvgIcon name="ik-sousuotianchong" />
            </template>
          </el-input>
        </div>
        <div class="list-icon">
          <div>
            <IkSvgIcon
              class="list-icon-item empty"
              name="iksvg_shanchu"
              size="big"
              type="error"
              pop
              title="删除已选图标"
              @click="removeIcon"
            />
          </div>
          <div
            v-for="(icon, index) in currentIconList"
            :key="index"
            class="icon-picker-div"
          >
            <IkSvgIcon
              :name="`${icon.class}`"
              size="big"
              class="list-icon-item"
              @click="chooseIcon(`${icon.class}`)"
              @mouseover="showPreviewIcon(`${icon.class}`, index + 1)"
              @mouseout="hidePreviewIcon"
            />
          </div>
          <IkSvgIcon
            class="list-icon-preview-item"
            size="50"
            :class="previewIcon && previewIconPosition"
            :name="previewIcon"
          />
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<style lang="scss">
.icon-picker-dialog {
  .el-dialog__header {
    background: var(--el-bg-color) !important;
    border-bottom: none !important;
  }

  .el-dialog__body {
    overflow-y: unset;
  }
}
</style>

<style lang="scss" scoped>
.el-icon {
  svg {
    height: 100%;
    width: 100%;
  }
}

.icon-picker {
  text-align: center;
  color: var(--el-text-color-regular);
  border: var(--el-border);
  border-radius: var(--el-border-radius-base);
  cursor: pointer;
  transition: 0.3s;
  font-size: var(--icon-picker-font-size);
  vertical-align: middle;

  &:hover {
    border: 1px solid var(--el-border-color-darker);
  }

  &.empty {
    color: var(--el-text-color-placeholder);
    border: 1px dashed var(--el-border-color);

    &:hover {
      color: var(--el-text-color-regular);
      border: 1px solid var(--el-border-color-darker);
    }
  }
}

.icon-picker-dialog-body {
  display: flex;
  height: 500px;
  margin: calc((var(--el-dialog-padding-primary) + 10px + 30px) * -1)
    calc(var(--el-dialog-padding-primary) * -1)
    calc((var(--el-dialog-padding-primary) + 10px) * -1)
    calc(var(--el-dialog-padding-primary) * -1);

  .el-tabs {
    :deep(.el-tabs__nav-prev),
    :deep(.el-tabs__nav-next) {
      background-image: linear-gradient(
        to right,
        transparent,
        var(--el-fill-color)
      );
    }

    :deep(.el-tabs__header .el-tabs__nav) {
      .el-tabs__active-bar {
        z-index: 0;
        width: 100%;
        background-color: unset;
        background-image: linear-gradient(
          to right,
          transparent,
          var(--el-fill-color)
        );
        border-right: 2px solid var(--el-color-primary);
        transition: 0.3s;
      }

      .el-tabs__item {
        position: relative;
        margin-bottom: -2px;
        height: auto;
        transition: 0.3s;

        &::after {
          content: '';
          position: absolute;
          left: 0;
          bottom: 0;
          width: 100%;
          height: 2px;
          background-image: linear-gradient(
            to right,
            transparent,
            var(--el-fill-color)
          );
        }

        .icon-label {
          display: flex;
          flex-direction: column;
          width: 120px;
          text-align: left;
          line-height: 20px;
          padding: 15px 0;

          .name {
            font-size: 16px;
            margin-bottom: 2px;
            white-space: normal;
            word-break: initial;
          }

          .total {
            font-size: 12px;
          }
        }
      }
    }
  }

  .main-container {
    flex: 1;
    margin-right: 15px;

    .search-bar {
      margin: 0 40px;

      .el-input {
        margin-top: 20px;
      }
    }

    .list-icon {
      position: relative;
      margin: 15px 0;
      min-height: 160px;
      overflow-y: auto;
      height: calc(100% - 91px);

      .icon-picker-div {
        margin: 4px;
        display: inline-flex;
        width: 40px;
        height: 40px;
        align-items: center;
        justify-content: center;
        border: 1px solid var(--ik-border-color);
        border-radius: 4px;
      }

      .list-icon-item {
        margin: 0;
        box-sizing: content-box;
        padding: 15px;
        font-size: 28px;
        cursor: pointer;
        transition: var(--el-transition-border);

        &:nth-child(6n + 6) {
          margin-right: 0;
        }

        &:not(.empty):hover {
          border-color: var(--el-border-color-darker);
          background-color: var(--el-fill-color);
          color: var(--el-color-primary);
          transition: background-color 0.3s, var(--el-transition-border),
            var(--el-transition-color);
        }

        &.empty {
          border-color: transparent;
          color: var(--el-text-color-placeholder);
          transition: var(--el-transition-color);

          &:hover {
            color: var(--el-text-color-disabled);
          }
        }
      }

      .list-icon-preview-item {
        display: none;
        position: absolute;
        box-sizing: content-box;
        padding: 10px;
        border: 1px solid var(--el-border-color-darker);
        font-size: 108px;
        background: var(--el-fill-color);
        color: var(--el-color-primary);
        align-items: center;
        justify-content: center;

        &.top-left {
          display: flex;
          top: 5px;
          left: 5px;
        }

        &.top-right {
          display: flex;
          top: 5px;
          right: 5px;
        }

        &.bottom-left {
          display: flex;
          bottom: 5px;
          left: 5px;
        }

        &.bottom-right {
          display: flex;
          bottom: 5px;
          right: 5px;
        }
      }
    }

    .el-pagination {
      display: flex;
      justify-content: center;
    }
  }
}
</style>
